import pygame
from pygame.sprite import Group

from scoreboard import Scoreboard
from ship import Ship


class GameStatus:
    """跟踪游戏的统计信息"""
    def __init__(self, ai_game):
        """初始化统计信息"""
        self.settings = ai_game.settings
        self.ai = ai_game
        self.high_score = 0
        self.level = 1
        # 分离初始化操作，用于运行期间重置
        self.reset_stats()
        # 任何情况下都不重置最高得分
        self.game_active = False
        # 初始化文本surface
        pygame.font.init()
        self.font = pygame.font.SysFont(self.settings.font,
                                        self.settings.font_size)
        self.big_font = pygame.font.SysFont(self.settings.font,
                                            self.settings.big_font_size)

    def reset_stats(self):
        """初始化在游戏运行期间可能发生变化的统计信息"""
        self.ship_lef = self.settings.ship_limit
        self.alien_number = self.settings.alien_number
        self.settings.initialize_dynamic_settings()
        self.score = 0
        self.scoreboard = Scoreboard(self)
        self.scoreboard.prep_score()

    def game_over(self):
        pass

    def _show_status(self):
        """显示参数信息"""
        # 分数板
        self.scoreboard.show_score()
        text = ""
        # 坐标
        x = self.ai.ship.rect.x
        y = self.ai.ship.rect.y
        w = self.settings.screen_width
        h = self.settings.screen_height
        text += f"ship:(x:{x},y:{y}) screen:[width:{w}, height:{h}] "
        # 发射模式
        if self.settings.bullets_allowed > 0:
            text += "Bullet Mode: limit "
        else:
            text += "Bullet Mode: unlimit "
        text += f"aliens: {self.alien_number} "
        text += f"ships: {self.ship_lef} "
        self._set_surface(text)
        # 子弹数量
        if len(self.ai.ship.bullets) > 0:
            self._set_surface(f"Bullets:{len(self.ai.ship.bullets)}", 0, 20)
        # 游戏结束
        # if not self.game_active and self.alien_number > 0:
        #     self._render_msg("Game Over")
        # elif not self.game_active and self.alien_number <= 0:
        #     self._render_msg("You win")

    def _set_surface(self, text, x_pos=0, y_pos=0):
        """向屏幕输出信息"""
        text_surface = self.font.render(text, False, (0, 0, 0))
        self.ai.screen.blit(text_surface, (x_pos, y_pos))

    def _render_msg(self, msg):
        """将msg渲染为图像"""
        text_color = (255, 0, 0)
        bg_color = (0, 0, 0)
        msg_imgae = self.big_font.render(msg, True, text_color, bg_color)
        msg_imgae.get_rect().center = self.ai.screen.get_rect().center

    def prep_ships(self):
        """图像显示剩余飞船数"""
        self.ships = Group()
        for ship_number in range(self.ship_lef):
            ship = Ship(self.ai)
            ship.rect.x = 10 + ship_number * ship.rect.width
            ship.rect.y = 10
            self.ships.add(ship)
